#!/usr/bin/perl
# 
# Description
#  Creates tags and cscope for the files in an obj file
#
# Author
#  Lori Song - Wood Eye Software
#
use strict;
use warnings;
use File::Basename;
use POSIX;
use constant DATETIME => strftime("%Y-%m-%d_%H-%M-%S", localtime);

die "Usage: $0 obj_file_name!"
   if(@ARGV != 1);

my $obj_file = shift @ARGV;

die "$obj_file does not exists!"
   unless -e $obj_file;

$obj_file = readlink($obj_file)
   if -l $obj_file;

# Get the Configuration Record from the obj file
print "cat $obj_file......\n";
my @conf_record = `cat $obj_file`;
die "$obj_file is not an obj file!"
   if!(@conf_record);

# Grep the source files
my @source_files = grep {/^.+\.(h|hpp|c|cc|sig|pm|cpp|inc)$/ && !/CMakeFile/} @conf_record;

if(@source_files){
   # Create session files under new folder ~/gvim_sessions/viewname_objname_DATETIME,
   my $view_name = `cleartool pwv -s`;
   chomp($view_name);
   my $session_dir_name = $view_name . "_" . basename $obj_file;
   $session_dir_name =~ s/\..*//g;
   $session_dir_name = glob("~") . "/gvim_sessions/" . $session_dir_name . "_" . DATETIME;
   
   print "Creating new session under $session_dir_name:\n"
      if (!system("mkdir -p $session_dir_name"));

   chdir $session_dir_name
      or die "Cannot chdir to $session_dir_name!";

   # Setup cscope database
   print "Setuping cscope database\n";
   open CSCOPE_FILES, ">>cscope.files"
     or die "Can not create cscope.files!";

   print CSCOPE_FILES  sort(@source_files);
   system("cscope -bq");

   close CSCOPE_FILES;

   # Setup tags
   print "Setuping tags\n";
   system("ctags -a --fields=+lS -L cscope.files 2> /dev/null");

   # Setup tag file for plugin LookupFile
   print "Setuping tag file for plugin LookupFile\n";
   open FILENAMETAGS, ">>filenametags"
      or die "Can not create filenametags!";

   foreach (@source_files){
      chomp;
      $_ = (basename $_) . "\t$_\t1\n";
   }
   @source_files = sort(@source_files);
   unshift(@source_files, "!_TAG_FILE_SORTED\t2\t/2=foldcase/\n");
   print FILENAMETAGS @source_files;

   close FILENAMETAGS;

   # Copy session template file to current directory
   print "Copying session template file\n";
   system("cp ../Session_template.vim ./Session.vim");
   system("cp ../Sessionx_template.vim ./Sessionx.vim");

   print "Done^-^\n";
}

